import React, {useRef, useState} from "react";
import {
    Image,
    TouchableOpacity,
    View,
    Text,
    Modal,
    StyleSheet,
    TouchableWithoutFeedback,
    UIManager,
    findNodeHandle,
    Dimensions,
} from "react-native";
import styles from "./index.style";
import {useEmojiActions, useEmojiState} from "@/hooks/emoji/user-emoji";
import {UserEmojiPackItemType} from "@/types/user-emoji";

const SCREEN = Dimensions.get("window");

interface CustomEmojiPreviewerProps {
    data: UserEmojiPackItemType
    onSelectEmoji?: (data: UserEmojiPackItemType) => void,
    onMoveTop?: () => void,
    onDelete?: () => void,
}

export default function CustomEmojiPreviewer({
                                                 data,
                                                 onSelectEmoji,
                                                 onMoveTop,
                                                 onDelete,
                                             }: CustomEmojiPreviewerProps) {
    const [modalVisible, setModalVisible] = useState(false);
    const [popupPos, setPopupPos] = useState({top: 0, left: 0});
    const [arrowLeft, setArrowLeft] = useState(0);
    const touchRef = useRef<View>(null);
    const {emojiItems} = useEmojiState();
    const {deleteEmojiItem, updateEmojiItem} = useEmojiActions();

    const showPopup = () => {
        const handle = findNodeHandle(touchRef.current);
        if (handle) {
            UIManager.measure(handle, (_x, _y, width, height, pageX, pageY) => {
                const popupWidth = 140;
                const popupHeight = 150;
                const ARROW_HEIGHT = 10;
                const GAP = 30;
                const arrowWidth = 12;

                let left = pageX + width / 2 - popupWidth / 2;
                let top = pageY - popupHeight - ARROW_HEIGHT - GAP;

                // 边界判断：避免弹窗超出屏幕左右
                if (left < 8) left = 8;
                if (left + popupWidth > SCREEN.width - 8) {
                    left = SCREEN.width - popupWidth - 8;
                }

                // 箭头位置：以原表情中心为基准，相对于弹窗左边
                const arrowOffset = pageX + width / 2 - left - arrowWidth / 2;
                setArrowLeft(arrowOffset);

                // 如果上方空间不足，就显示在下方（可扩展）
                if (top < 8) {
                    top = pageY + height + ARROW_HEIGHT + GAP;
                }

                setPopupPos({top, left});
                setModalVisible(true);
            });
        }
    };

    const closeModal = () => {
        setModalVisible(false);
    };

    return (
        <>
            <TouchableOpacity
                ref={touchRef}
                onPress={() => onSelectEmoji?.(data)}
                onLongPress={showPopup}
                style={styles.stickerContainer}
            >
                <Image source={{uri: data.filePath}} style={styles.stickerImage}/>
            </TouchableOpacity>

            <Modal visible={modalVisible} transparent animationType="fade">
                <TouchableWithoutFeedback onPress={closeModal}>
                    <View style={popupStyles.fullScreen}>
                        <View
                            style={[
                                popupStyles.popupContainer,
                                {top: popupPos.top, left: popupPos.left},
                            ]}
                        >
                            <Image source={{uri: data.filePath}} style={popupStyles.previewImage}/>
                            <View style={popupStyles.buttonRow}>
                                <TouchableOpacity
                                    onPress={async () => {
                                        closeModal();
                                        const maxSortOrder = Math.max(...emojiItems.map(item => item.sortOrder), 0);
                                        await updateEmojiItem({
                                            id: data.id,
                                            sortOrder: maxSortOrder + 1,
                                        });
                                        onMoveTop?.();
                                    }}
                                >
                                    <Text style={popupStyles.optionText}>移动前面</Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    onPress={async () => {
                                        closeModal();
                                        await deleteEmojiItem(data.id)
                                        onDelete?.();
                                    }}
                                >
                                    <Text style={[popupStyles.optionText, {color: "#e74c3c"}]}>
                                        删除
                                    </Text>
                                </TouchableOpacity>
                            </View>
                            <View style={[popupStyles.arrow, {left: arrowLeft}]}/>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </Modal>
        </>
    );
}

const popupStyles = StyleSheet.create({
    fullScreen: {
        flex: 1,
    },
    popupContainer: {
        position: "absolute",
        width: 140,
        backgroundColor: "#fff",
        borderRadius: 10,
        padding: 10,
        elevation: 5,
        shadowColor: "#000",
        shadowOpacity: 0.2,
        shadowRadius: 6,
        alignItems: "center",
    },
    previewImage: {
        width: 100,
        height: 100,
        borderRadius: 10,
        marginBottom: 10,
    },
    buttonRow: {
        flexDirection: "row",
        justifyContent: "space-between",
        width: "100%",
        gap: 10,
    },
    optionText: {
        fontSize: 16,
        color: "#333",
    },
    arrow: {
        position: "absolute",
        bottom: -10,
        width: 0,
        height: 0,
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderTopWidth: 10,
        borderLeftColor: "transparent",
        borderRightColor: "transparent",
        borderTopColor: "#fff", // 匹配弹窗背景
    },
});
